/*
 * @Author: heinan
 * @Date: 2023-07-25 19:10:55
 * @Last Modified by: heinan
 * @Last Modified time: 2023-08-03 18:21:14
 */

"use strict";
const { Service } = require("egg");
const { idCreator } = require("../utils/");

class InfoService extends Service {
  async index({ title, status, currentPage, pageSize }) {
    const where = {};
    if (title) {
      where.title = title;
    }
    if (!status || status == undefined) {
      delete where.status;
    } else {
      where.status = status;
    }
    const result = await this.app.mysql.select("infos", {
      where,
      offset: (currentPage - 1) * pageSize,
      limit: parseInt(pageSize),
    });
    const total = await this.app.mysql.count("infos", where);
    return {
      total,
      pageSize: Number(pageSize),
      currentPage: Number(currentPage),
      data: result,
    };
  }
  async destory({ id }) {
    return await this.app.mysql.delete("infos", { id });
  }
  async create({ uid, title, articel }) {
    const articel_id = idCreator();
    await this.ctx.service.articel.create({
      articel_id,
      articel_text: articel,
    });
    const $data = {
      id: idCreator(),
      uid,
      title,
      create_time: new Date().getTime(),
      update_time: new Date().getTime(),
      articel_id,
    };
    return await this.app.mysql.insert("infos", $data);
  }
  async update({ id, title, articel }) {
    // 根据资讯id查找资讯对应的文章id
    const info = await this.find(id);
    const $data = { id, title };
    $data.update_time = new Date().getTime();
    const updInfomation = await this.app.mysql.update("infos", $data);
    // 根据找到的资讯对应的文章id，修改文章内容
    const updArticel = await this.app.mysql.update(
      "articel",
      { articel_text: articel },
      { where: { articel_id: info.articel_id } }
    );
    // 等待两个事务的结束，全都成立返回 true|false
    return Promise.all([updInfomation, updArticel]).then((p) => {
      return p.every((result) => result.affectedRows > 0);
    });
  }
  async show({ id }) {
    const $sql = `SELECT users.nickname,infos.id,infos.title,articel.articel_id,articel.articel_text,infos.create_time,infos.update_time FROM infos,articel,users WHERE infos.uid=users.id AND infos.articel_id=articel.articel_id AND infos.articel_id=?`;
    return await this.app.mysql.query($sql, [id]);
  }
  async find(id) {
    return await this.app.mysql.get("infos", { id });
  }
}

module.exports = InfoService;

